package com.cashmama.market.api.infras.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

/**
 * http请求
 *
 * @author liuming
 * Created on 下午3:47 2018/9/3.
 */
public class IFSCHttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(IFSCHttpUtil.class);

    private final static String IFSC_REQUEST_URL = "https://ifsc.razorpay.com/";

    /**
     * 校验IFSC
     *
     * @param ifsc
     * @return String 所代表远程资源的响应结果
     */
    public static String sendGet(String ifsc) {
        String responseJson = null;
        CloseableHttpResponse response = null;
        try {
            CloseableHttpClient client = getHttpClient();
            HttpGet httpGet = new HttpGet(IFSC_REQUEST_URL + ifsc);
            logger.info("------ ifsc check http get, ifsc:{} ------", ifsc);
            response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            logger.info("------ ifsc check http get status:{} ------", statusCode);
            if (statusCode == HttpStatus.SC_NOT_FOUND) {
                return null;
            }
            HttpEntity entity = response.getEntity();
            responseJson = EntityUtils.toString(entity, "utf8");
        } catch (Exception e) {
            logger.info("------ ifsc check http get exception ------", e);
            throw new RuntimeException("ifsc check http get exception");
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.info("------ ifsc check http get close resource exception ------", e);
                }
            }
        }
        return responseJson;
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("TLS");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }

    /**
     * 获取HttpClient
     *
     * @return
     */
    private static CloseableHttpClient getHttpClient() {
        //采用绕过验证的方式处理https请求
        SSLContext sslcontext = null;
        try {
            sslcontext = createIgnoreVerifySSL();
        } catch (Exception e) {
            logger.info("------ ifsc get http client exception ------", e);
        }

        // 设置协议http和https对应的处理socket链接工厂的对象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslcontext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        HttpClients.custom().setConnectionManager(connManager);

        //创建自定义的httpclient对象
        return HttpClients.custom().setConnectionManager(connManager).build();
    }
}
